import Snake, { snakes } from "./Snake.js";
import Bug from "./Bug.js";
import Canvas from "./Canvas.js";
import config from "./config.js";
import Play from "./Play.js";
export default class App {
  constructor(options) {
    Object.assign(config, options);
    this.validate();
    //创建画布
    this.$canvas = new Canvas(this);
    //创建小蛇
    this.snake({ bgColor: "green", ...this.randomPosition() });
    //创建小虫
    this.bug();
    //动画控制
    new Play(this);
    this.totalElement = this.createTotalElement();
  }

  createTotalElement() {
    const div = document.createElement("div");
    div.innerHTML = "加油";
    document.body.insertAdjacentElement("afterbegin", div);
    return div;
  }
  // 生成小虫的坐标，并不会与已经在蛇位置重复
  bug() {
    let position;
    while ((position = this.randomPosition())) {
      let state = snakes.some(
        (snake) => snake.left == position.left && snake.top == position.top
      );

      if (!state) break;
    }
    let bug = new Bug(this.$canvas, position);
    this.$canvas.$el.insertAdjacentElement("beforeEnd", bug.$el);
  }

  snake(options) {
    //创建小蛇
    let snake = new Snake(this, options);
    this.$canvas.$el.insertAdjacentElement("beforeEnd", snake.$el);
  }
  //验证用户参数
  validate() {
    if (config.canvas.width % config.width) {
      throw new Error("尺寸与格子大小必须要整除");
    }
  }

  // 生成随机坐标位置
  randomPosition() {
    let left =
      Math.floor(Math.random() * (config.canvas.width / config.width)) *
      config.width;
    let top =
      Math.floor(Math.random() * (config.canvas.height / config.height)) *
      config.height;
    return { left, top };
  }

  renderTotal(content = "") {
    this.totalElement.textContent = content + `你共吃掉 ${Snake.count}个`;
  }
}
